import React ,{useState} from 'react'
import { Link } from 'react-router-dom'
import {adminnameExist,login} from '../../services/admin'
import { useNavigate } from "react-router-dom";

export default  function (props) {
    const navigate = useNavigate();
    const handleLogin = async () => {
        if(adminName.info==='√'&&adminPassword.info==='√'){
            let result = await login({adminName:adminName.value,adminPassword:adminPassword.value})
            console.log(result)
            if(result.code==='0') navigate('/system')
        }else{
        }
    }
    const [adminName, setAdminName] = useState({
        info:'账号由4-20位字符组成',
        value:''
    })
    const [adminPassword, setAdminPassword] = useState({
        info:'密码由6-20位字符组成',
        value:''
    })

   
   const saveAdminName = async (e) => {
    let result = await adminnameExist(e.target.value)
    if(/^\w{4,20}$/.test(e.target.value)){
        result.code==='1'?setAdminName({info:'√',value:e.target.value}):
        setAdminName({info:result.message,value:e.target.value})
    }else{
        setAdminName({info:'×',value:e.target.value})
    }
}
   const saveAdminPassword = (e) => {
    setAdminPassword(e.target.value)
    if (/^\w{6,20}$/.test(e.target.value)&&e.target.value!=='') {
        setAdminPassword({info:'√',value:e.target.value})
    } else {
        setAdminPassword({info:'×',value:e.target.value})
    }
    }
    return (
        <div>
            <p>
                <label>账号：</label>
                <input type='text' onBlur={saveAdminName}/>
                <span>{adminName.info}</span>
            </p>
            <p>
                <label>密码：</label>
                <input type='password' onBlur={saveAdminPassword}/>
                <span>{adminPassword.info}</span>
            </p>
           <button onClick={handleLogin}>登录</button>
           <button> <Link to='/register'>注册</Link></button>
        </div>
        
    )

}
